import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flutter/material.dart';
import 'package:study_demo/ui/game/liveable.dart';

class HeroComponent extends SpriteAnimationComponent with HasGameRef, Liveable {
  HeroComponent() : super(size: Vector2(50, 37), anchor: Anchor.center);

  @override
  Future<void> onLoad() async {
    List<Sprite> sprites = [];
    for (int i = 0; i <= 8; i++) {
      sprites.add(await Sprite.load('adventurer/adventurer-bow-0$i.png'));
    }
    animation = SpriteAnimation.spriteList(sprites, stepTime: 0.15);
    position = gameRef.size / 2;
    initPaint(lifeColor: Colors.blue, lifePoint: 1000);
  }

  double speed = 200.0;

  @override
  void onGameResize(Vector2 gameSize) {
    super.onGameResize(gameSize);
    position.x = gameSize.x / 3;
  }

  move(Vector2 ds) {
    position.add(ds);
  }

  rotateTo(double deg) {
    angle = deg;
  }

  flip({bool x = false, bool y = true}) {
    scale = Vector2(scale.x * (y ? -1 : 1), scale.y * (x ? -1 : 1));
  }

  final double _speed = 100;

  void toTarget(Vector2 target) {
    removeAll(children.whereType<MoveEffect>());
    double timeMs = (target - position).length / _speed;
    add(
      MoveEffect.to(
        target,
        EffectController(
          duration: timeMs,
        ),
      ),
    );
  }
}

class Monster extends SpriteAnimationComponent with Liveable {
  Monster({
    required SpriteAnimation animation,
    required Vector2 size,
    required Vector2 position,
  }) : super(
          animation: animation,
          size: size,
          position: position,
          anchor: Anchor.center,
        );

  @override
  Future<void> onLoad() async {
    add(RectangleHitbox()..debugMode = false);
    initPaint(lifeColor: Colors.redAccent, lifePoint: 1000);
  }

  // double _speed = 150;
  //
  // @override
  // void update(double dt) {
  //   super.update(dt);
  //   Vector2 ds = Vector2(-1, 0) * _speed * dt;
  //   move(ds);
  //   if (position.x + size.x / 2 < 0) {
  //     removeFromParent();
  //   }
  // }
  //
  // void move(Vector2 ds) {
  //   position.add(ds);
  // }

  @override
  void onDied() {
    removeFromParent();
  }
}
